package person.zjh.gulimall.product.service.impl;

import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import person.zjh.gulimall.utils.PageUtils;
import person.zjh.gulimall.utils.Query;

import person.zjh.gulimall.product.dao.CategoryDao;
import person.zjh.gulimall.product.entity.CategoryEntity;
import person.zjh.gulimall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {


    @Override
    public List<CategoryEntity> listWithTree() {
        //首先查询出所有的分类数据
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
        //然后进行树形结构的组装
        //找到所有一级菜单
        List<CategoryEntity> levelMenu = categoryEntities
                .stream()
                .filter(item -> item.getParentCid() == 0)
                .map(menu->{
                    menu.setChildrenList(findChildrenList(menu,categoryEntities));
                    return menu;
                })
                .sorted(Comparator.comparingInt(CategoryEntity::getSort))
                .collect(Collectors.toList());

        return categoryEntities;
    }


    List<CategoryEntity> findChildrenList(CategoryEntity root,List<CategoryEntity> categoryEntityList){
        List<CategoryEntity> childrenList = categoryEntityList.stream()
                .filter(menu -> Objects.equals(menu.getParentCid(), root.getCatId()))
                .map(category -> {
                    category.setChildrenList(findChildrenList(category, categoryEntityList));
                    return category;
                })
                .sorted(Comparator.comparingInt(CategoryEntity::getSort))
                .collect(Collectors.toList());
        return childrenList;
    }



}